<!--
  - Copyright (c) 2018.
  - 北京九思金信科技有限公司对该文件内容保留所有权利。
  - 未经许可，不得私自拷贝、传播、发布、引用该文件内容，违者将被追究法律责任。
  -->

<template>
  <div>
    <el-autocomplete
      popper-class="my-autocomplete"
      v-model="customerManagerName"
      :placeholder="placeholder"
      :fetch-suggestions="querySearch"
      @change="changeVal"
      size="small"
      v-if="editable"
      style="width: 100%"
      @select="handleSelect">
      <template slot-scope="{ item }">
        <div class="name">{{ item.userName }}</div>
        <span class="addr">{{ item.deptName }}</span>
      </template>
    </el-autocomplete>
    <span v-if="!editable" style="padding: 8px 0px 8px 8px">{{customerManagerName}}</span>
  </div>
</template>

<script>
  export default {
    name: "FtUserWithFilter",
    props: ["placeholder","value","editable","customerManagerId","matchAfterInput", "filter"],
    mounted() {
      this.load()
    },

    data() {
      return {
        user: {},
        userbak: {},
        userArr: [],
        customerManagerName: null,
        data: [],
        dataInit: [],
      }
    },
    methods: {
      //加载所有客户经理选项
      load(val) {
        let params = {
            filter: val
        }
        this.$http.get('/joys-rest/lss-customer/custInfo/manager/filter', {params}).then(
          resp => {
            this.data = resp.body
            if(this.customerManagerId && this.customerManagerId != ''){
              this.matchCustomerInit(this, this.customerManagerId)
            }
          }, resp => {
            this.$message.error('获取客户经理列表失败')
          }
        )
      },
      //匹配建议选项
      querySearch(queryString, cb) {
        var restaurants = this.data
        var results = []
        // matchAfterInput 是否在输入内容后再显示下拉提示
        if(this.matchAfterInput && '' == queryString ){
          cb(results)
        }else{
          results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
          if (results.length == 0) {
            this.customerManagerName = ''
          }
          // 调用 callback 返回建议列表的数据
          cb(results)
        }
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.userName.toLowerCase().indexOf(queryString.toLowerCase()) != -1)
        }
      },
      change(){
        this.$emit('input', this.customerManagerName)
        this.$emit('change', this.customerManagerName)
      },
      //点选建议选项
      handleSelect(item) {
        this.customerManagerName = item.userName
        this.userbak = JSON.parse(JSON.stringify(item))
        this.$emit('matchedOption', item)
      },
      //失去焦点时匹配项目经理，如果存在多条则匹配不成功，返回输入前记录
      changeVal() {
        const _this = this
        this.$nextTick(() => {
          this.matchCustomer(_this, _this.customerManagerName)
        })
      },
      matchCustomer(_this, val){
        if(val == ''){
          _this.$emit('matchedOption',{})
          return
        }
        _this.userArr = _this.data.filter(item => {
          return item.userName == val
        })
        if(_this.userArr.length == 1){
          _this.userbak = JSON.parse(JSON.stringify(_this.userArr[0]))
          _this.$emit('matchedOption', _this.userArr[0])
        }else{
          this.customerManagerName = _this.userbak.userName
          _this.$emit('unmatchedOption', {customerManagerName: _this.userbak})
        }
      },
      //根据传入ID匹配客户经理
      matchCustomerInit(_this, val){
        _this.user = _this.data.filter(item => {
          return item.userId == val
        })
        if(_this.user.length > 0){
          _this.customerManagerName = _this.user[0].userName
          _this.userbak = JSON.parse(JSON.stringify(_this.user[0]))
          _this.$emit('matchedOption', _this.user[0])
        }else{
          _this.customerManagerName = ''
          _this.userbak = {}
          _this.$emit('matchedOption', {})
        }
      },
    },
    watch: {
      customerManagerId: {
        handler(val) {
          const _this = this
          if(val == '' || !val){
            _this.customerManagerName = ''
            _this.userbak = {}
            _this.$emit('matchedOption', {})
            return
          }
          if(val != '' && _this.data.length > 0){
            _this.matchCustomerInit(_this, this.customerManagerId)
          }
        },
        immediate: true
      },
      // 手动清空用户名称，则清空用户id，即清空父组件已绑定的用户id值
      customerManagerName:{
        handler(val) {
          if(!val){
            this.$emit('matchedOption', {userId:null})
          }
        }
      }
    }
  }
</script>
<style>
  .my-autocomplete.el-autocomplete-suggestion li {
    line-height: normal;
    padding: 7px;
  }
  .my-autocomplete.el-autocomplete-suggestion .name {
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .my-autocomplete.el-autocomplete-suggestion .addr {
    font-size: 12px;
    color: #b4b4b4;
  }

  .my-autocomplete.el-autocomplete-suggestion.highlighted .addr {
    color: #ddd;
  }

</style>
<style scoped>

</style>
